﻿using Infrastructure.DbUtility;
using Infrastructure.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

public partial class admin_question_edit : BasePage
{

    protected int ChapterId
    {
        get { return ViewState["ChapterId"] == null ? 0 : (int)ViewState["ChapterId"]; }
        set { ViewState["ChapterId"] = value; }
    }

    protected string ChapterTitle
    {
        get { return ViewState["ChapterTitle"] == null ? string.Empty : (string)ViewState["ChapterTitle"]; }
        set { ViewState["ChapterTitle"] = value; }
    }
    protected string ChapterGrade
    {
        get { return ViewState["ChapterGrade"] == null ? string.Empty : (string)ViewState["ChapterGrade"]; }
        set { ViewState["ChapterGrade"] = value; }
    }

    protected string ChapterSubject
    {
        get { return ViewState["ChapterSubject"] == null ? string.Empty : (string)ViewState["ChapterSubject"]; }
        set { ViewState["ChapterSubject"] = value; }
    }

    protected string ChapterPart
    {
        get { return ViewState["ChapterPart"] == null ? string.Empty : (string)ViewState["ChapterPart"]; }
        set { ViewState["ChapterPart"] = value; }
    }

    protected decimal ChapterPractice
    {
        get { return ViewState["ChapterPractice"] == null ? 0M : (decimal)ViewState["ChapterPractice"]; }
        set { ViewState["ChapterPractice"] = value; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int cid = 0;
            if (int.TryParse(Request["cid"], out  cid) && cid > 0) this.LoadChapter(cid);
        }
    }

    private void LoadChapter(int cid)
    {
        //获取章节数据
        string sql = "SELECT * FROM Chapter (NOLOCK) WHERE cid=" + cid;
        DbHelper db = new DbHelper();
        var table = db.ExecQuery(sql);
        if (table != null && table.Rows.Count > 0)
        {
            ChapterId = cid;
            ChapterTitle = table.Rows[0].Value("title");
            ChapterGrade = table.Rows[0].Value("gname");
            ChapterSubject = table.Rows[0].Value("subjectname");
            ChapterPart = table.Rows[0].Value("part");
            ChapterPractice = table.Rows[0].Value<int>("pid");
            Entity["cid"] = cid;
            //获取练习题数据
            int qid = 0;
            int.TryParse(Request["qid"], out qid);
            sql = "SELECT * FROM Question (NOLOCK) WHERE qid = " + qid;
            table = db.ExecQuery(sql);
            if (table != null && table.Rows.Count > 0)
            {
                foreach (DataColumn col in table.Columns) Entity[col.ColumnName] = table.Rows[0][col];
                //获取选项
                sql = "SELECT * FROM QuestionOption (NOLOCK) WHERE pid = " + qid;
                var tbOptions = db.ExecQuery(sql);

                var list = tbOptions.AsEnumerable().Select(r => new { oid = r.Value<int>("oid"), answer = r.Value("answer"), right = r.Value("right"), score = r.Value<decimal>("score") }).ToList();
                if (list.Count == 0) this.listOptions.DataSource = new List<object>() { new { oid = "0_1", answer = string.Empty, right = string.Empty, score = 0 } };
                else this.listOptions.DataSource = list;
                this.listOptions.DataBind();

                if (table != null && table.Rows.Count > 0 && tbOptions != null && tbOptions.Rows.Count > 0 && table.Rows[0].Value<int>("type") == 3) Entity["rightanswer"] = tbOptions.Rows[0].Value("right");
            }
            else
            {
                var t = 0;
                int.TryParse(Request["type"], out t);
                this.Entity["type"] = t;
                this.listOptions.DataSource = new List<object>() { new { oid = "0_1", answer = string.Empty, right = string.Empty, score = 0 } };
                this.listOptions.DataBind();
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        var cid = 0;
        var qid = 0M;
        var type = 0;
        var title = string.Empty;
        var content = Request["content"];
        decimal score = 0M;//M后缀表示一个  decimal数据类型的数字。
        var creator = 1;
        var status = 1;
        var right = Request["right"];

        int.TryParse(Request["cid"], out  cid);
        decimal.TryParse(Request["qid"], out  qid);
        int.TryParse("0" + Request["type"][0], out  type);
        if (type != 2) title = Request["title1"];
        else title = Request["title2"];
        decimal.TryParse(Request["score"], out score);

        List<QuestionOption> options = type != 3 ? this.GetOptions() : this.GetTextareaAnswer(score);
        DbHelper db = new DbHelper();
        db.BeginTransaction();
        if (ChapterPractice <= 0)
        {
            var pid = (decimal)db.ExecuteScalarEx("INSERT INTO PracticeForm (pname,description,creator) VALUES ({0},{1},{2}) SELECT @@IDENTITY", ChapterPart + "练习题", string.Empty, creator);
            db.ExecuteUpdate("UPDATE Chapter SET pid = " + pid + " WHERE cid = " + cid);
            ChapterPractice = pid;
        }


        if (qid == 0)
        {
            string sql = "INSERT INTO Question ([type],title,content,score,parentid,creator,[status]) VALUES ({0},{1},{2},{3},{4},{5},{6}) SELECT @@IDENTITY";
            qid = (decimal)db.ExecuteScalarEx(sql, type, title, content, score, 0, creator, status);
            db.ExecuteUpdateEx("INSERT INTO PracticeQuestion (pid,qid) VALUES ({0},{1})", ChapterPractice, qid);
        }
        else
        {
            db.ExecuteUpdateEx("UPDATE Question SET [type] = {0},title = {1},content = {2},score = {3},parentid = {4},creator = {5},[status] = {6} WHERE qid = {7}", type, title, content, score, 0, creator, status, qid);
        }

        db.ExecuteUpdate("DELETE FROM QuestionOption WHERE pid = " + qid);
        foreach (QuestionOption option in options)
        {
            string osql = "INSERT INTO QuestionOption ([pid],[answer],[right],[score],[creator]) VALUES ({0},{1},{2},{3},{4})";
            db.ExecuteUpdateEx(osql, qid, option.Answer, option.Right, option.Score, creator);
        }
        db.CommitTransation();
        //do save
        Response.Redirect(Request.RawUrl);
    }
    private List<QuestionOption> GetTextareaAnswer(decimal score)
    {
        return new List<QuestionOption>() { 
            new QuestionOption{ Id = 0, Answer = Request["right"] ?? string.Empty, Right = Request["right"] ?? string.Empty, Score = score }
        };
    }
    private List<QuestionOption> GetOptions()
    {
        var listOptions = new List<QuestionOption>();
        var optionKeys = Request.Form.AllKeys.Where(k => k.StartsWith("option_"));
        foreach (string k in optionKeys)
        {
            var id = k.Substring(7);
            if (id.StartsWith("0_"))
            {
                //新选项
                listOptions.Add(new QuestionOption {
                    Id = 0,
                    Answer = Request[k],
                    Right = Request["chk_option_" + id] == "1" ? Request[k] : string.Empty,
                    Score = decimal.Parse("0" + Request["score_option_" + id])
                });
            }
            else
            {
                //原有选项
                listOptions.Add(new QuestionOption {
                    Id = int.Parse(id),
                    Answer = Request[k],
                    Right = Request["chk_option_" + id] == "1" ? Request[k] : string.Empty,
                    Score = decimal.Parse("0" + Request["score_option_" + id])
                });
            }
        }
        return listOptions;
    }

    public class QuestionOption
    {
        public int Id { get; set; }
        public decimal Score { get; set; }
        public string Answer { get; set; }
        public string Right { get; set; }
    }
}